package com.zyguo.sdk.websocket;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

import org.apache.log4j.Logger;



public class ResponseLock {
	private ReentrantLock lock = new ReentrantLock();
	private Condition condition = lock.newCondition();
	private ResponseMsg responseMsg;
	private Logger log = Logger.getLogger( ResponseLock.class );
	private int waitTime = 1000;
	
	public ResponseLock(){
		
	}
	
	public ResponseLock( int waitTime ){
		this.waitTime = waitTime;
	}
	
	public void setResponseMsg( ResponseMsg responseMsg ){
		log.debug( "setResponseMsg, responseMsg=" + responseMsg );
		lock.lock();
		try {
			this.responseMsg = responseMsg;
			condition.signal();
		} catch (Exception e) {
			log.error("setResponseMsg， 异常", e);
		} finally{
			lock.unlock();
		}
	}
	
	public ResponseMsg getResponseMsg(){
		log.debug( "getResponse===============" );
		lock.lock();
		try {
			condition.await( waitTime , TimeUnit.MILLISECONDS );
			/*
			while (responseMsg == null ) {
				condition.await();
			}
			*/
			log.debug( "getResponseMsg===============after wait, responseMsg=" + responseMsg );
			condition.signal();
			log.debug( "getResponseMsg===============after signal, responseMsg=" + responseMsg );
			return this.responseMsg;
		} catch (Exception e) {
			log.error("setResponseMsg, 异常", e);
		} finally{
			lock.unlock();
		}
		return null;
	}
}
